<?php

namespace App\Http\Controllers\Crm;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()){
            $data = $request->all(['name','contact_name','contact_phone']);
            $res = Product::query()
                ->orderByDesc('id')
                ->get();
            return $this->success('ok',$res,$res->count());
        }
        return View::make('crm.product.index');
    }

    public function create(Request $request)
    {
        $parentId = $request->input('parent_id',0);
        return View::make('crm.product.create',compact('parentId'));
    }

    public function store(Request $request)
    {
        try {
            $data = $request->all([
                'parent_id',
                'name',
                'description',
                'price'
            ]);
            Product::create($data);
            return $this->success();
        }catch (\Exception $exception){
            Log::error('添加产品异常：'.$exception->getMessage());
            return $this->error();
        }
    }

    public function edit(Request $request,$id)
    {
        $model = Product::query()->findOrFail($id);
        return View::make('crm.product.edit',compact('model'));
    }

    public function update(Request $request,$id)
    {
        try {
            $model = Product::query()->findOrFail($id);
            $data = $request->all([
                'name',
                'description',
                'price'
            ]);
            $model->update($data);
            return $this->success();
        }catch (\Exception $exception){
            Log::error('更新产品异常：'.$exception->getMessage());
            return $this->error();
        }
    }

    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)){
            return $this->error('请选择删除项');
        }
        try{
            Product::destroy($ids);
            return $this->success();
        }catch (\Exception $exception){
            Log::error('删除产品异常：'.$exception->getMessage());
            return $this->error();
        }
    }

}
